<template>
	<view class="container">
		<scroll-view scroll-y class="scroll-container">

			<!-- 只读日历 -->
			<uni-calendar :lunar="false" @change="handleDateChange" :date="currentDate" :selected="selectedDates"
				@monthSwitch="handleMonthSwitch" :showMonth="false" mode="date" :disableDate="true" />
			</uni-calendar>

			<!-- 分组展示区域 -->
			<view class="duty-section">
				<view v-for="group in currentGroups" :key="group.groupType" class="group-card">
					<view class="group-header">
						<text class="group-name">{{ group.groupName }}</text>
						<text class="driver-count">共{{ group.members.length }}人</text>
					</view>
					<view v-if="group.members.length > 0" class="driver-list">
						<text v-for="driver in group.members" :key="driver.id"
							:class="['driver-item', { highlighted: driver.name === currentUserName }]">
							{{ driver.name }}
						</text>
					</view>
					<view v-else class="empty-text">
						暂无值班司机
					</view>
				</view>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				loading: false,
				currentDate: '',
				selectedDates: [], // 已排班日期
				scheduleData: {}, // 所有排班数据
				drivers: [], // 所有司机基础信息
				currentUserName: uni.getStorageSync('userInfo')?.username || '', // 当前登录人姓名
			};
		},
		computed: {
			currentGroups() {
				const date = this.currentDate;
				const data = this.scheduleData[date]?.groups || [];
				return data.map(group => ({
					...group,
					members: group.members.map(member => {
						const driver = this.drivers.find(d => d.id === member.id);
						return {
							id: member.id,
							name: driver ? driver.name : '未知司机'
						};
					})
				}));
			}
		},
		watch: {
			currentDate(newDate) {
				if (newDate && !this.scheduleData[newDate]) {
					this.loadDutyData(newDate); // 按需加载
				}
			}
		},
		created() {
			this.initData();
		},
		methods: {
			async initData() {
				const today = this.getDateString(new Date());
				this.currentDate = today;
				await this.loadDriverData();
				await this.loadDutyData(today);
			},
			getDateString(date) {
				const y = date.getFullYear();
				const m = String(date.getMonth() + 1).padStart(2, '0');
				const d = String(date.getDate()).padStart(2, '0');
				return `${y}-${m}-${d}`;
			},
			async loadDriverData() {
				try {
					const obj = uniCloud.importObject('driver');
					const res = await obj.getDriverList();
					if (res.code === 0) {
						this.drivers = res.data.map(d => ({
							id: d._id,
							name: d.name
						}));
					} else {
						uni.showToast({
							title: '司机数据加载失败',
							icon: 'none'
						});
					}
				} catch (e) {
					//console.error('加载司机出错:', e);
				}
			},
			async loadDutyData(selectedDate) {
				const [year, month] = selectedDate.split('-');
				const startDate = `${year}-${month}-01`;
				const endDate = `${year}-${month}-${new Date(year, month, 0).getDate()}`;

				this.loading = true;
				try {
					const obj = uniCloud.importObject('duty');
					const res = await obj.getDutyDriver({
						startDate,
						endDate
					});

					if (res.code === 0) {
						res.data.forEach(item => {
							const date = item.data?.date;
							if (date && this.isValidDate(date)) {
								this.$set(this.scheduleData, date, {
									groups: item.data.groups
								});
							}
						});

						// 设置已排班日期
						this.selectedDates = res.data
							.filter(item => this.isValidDate(item.data.date)) // ✅ 使用 item.data.date
							.map(item => ({
								date: item.data.date, // ✅ 使用 item.data.date
								info: '已排班'
							}));
					} else {
						uni.showToast({
							title: '排班数据加载失败',
							icon: 'none'
						});
					}
				} catch (e) {
					//console.error('加载排班出错:', e);
				} finally {
					this.loading = false;
				}
			},
			isValidDate(dateString) {
				const reg = /^\d{4}-\d{2}-\d{2}$/;
				return dateString && reg.test(dateString);
			},
			handleDateChange(e) {
				const date = e.fulldate;
				if (this.isValidDate(date)) {
					this.currentDate = date;
				}
			},
			handleMonthSwitch(e) {
				// //console.log(e,'handleMonthSwitch')
				const year = e.year;
				const month = String(e.month).padStart(2, '0'); // 补零，如 4 → '04'
				const day = '01'; // 固定第一天
				const selectedDateStr = `${year}-${month}-${day}`;
				//console.log(selectedDateStr, 'handleMonthSwitch')
				this.loadDutyData(selectedDateStr)
			},
		}
	};
</script>

<style lang="scss" scoped>
	.container {
		height: 100%;
		/* 关键：继承父容器高度 */
	}

	.scroll-container {
		height: 100%;
		/* 继承父容器高度 */
		/* 原有其他样式保持不变 */
	}

	.badge {
		display: block;
		font-size: 10px;
		color: #007AFF;
		text-align: center;
		margin-top: 2px;
	}

	.duty-section {
		margin-top: 30rpx;
	}

	.group-card {
		background-color: #f9f9f9;
		border-radius: 12rpx;
		padding: 20rpx;
		margin-bottom: 30rpx;
		box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
	}

	.group-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20rpx;
	}

	.group-name {
		font-weight: bold;
		font-size: 16px;
		color: #333;
	}

	.driver-count {
		font-size: 14px;
		color: #888;
	}

	.driver-list {
		display: flex;
		flex-wrap: wrap;
		gap: 15rpx;
	}

	.driver-item {
		background-color: #e8f4ff;
		color: #333;
		padding: 8rpx 20rpx;
		border-radius: 40rpx;
		font-size: 14px;
		transition: all 0.3s ease;

		&.highlighted {
			background-color: #ffd700; // 黄色高亮
			font-weight: bold;
			color: #000;
		}
	}

	.empty-text {
		color: #999;
		font-size: 14px;
		text-align: center;
	}
</style>